/**
 * Project  : Looker
 * Package  : net.freestu.looker.impl
 * File     : FileMediaListener.java
 * Author   : solosky < solosky772@qq.com >
 * Date     : 2009-9-4
 * Modified : 2009-9-4
 * License  : Apache License 2.0 
 */
package net.freestu.looker.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Calendar;

import net.freestu.looker.common.ListenerException;
import net.freestu.looker.common.Media;
import net.freestu.looker.common.MediaListener;
import net.freestu.looker.util.FileUtils;
import net.freestu.looker.util.URLUtils;

import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;

/**
 *  复制附件到有命名规则的目录中，便于查找
 *  规则: www.domain.com/2009-09-02/IMAGE/126442155_fileName.jpg
 */
public class FileMediaListener implements MediaListener
{

	/**
	 * 附件保存的根目录
	 */
	private String mediaSaveRoot;
	
	/**
	 * 日志记录对象
	 */
	private static Logger logger = Logger.getLogger(FileMediaListener.class);
	
	/* (non-Javadoc)
     * @see net.freestu.looker.common.MediaListener#add(net.freestu.looker.common.Media)
     */
    @Override
    public void add(Media media) throws ListenerException
    {
    	File src = getSaveFile(media);
    	try {
	       FileUtils.copyTo(media.getTmpFile(),src );
    	} catch (FileNotFoundException e) {
	       throw new ListenerException("临时文件不存在:"+e.getMessage());
        } catch (IOException e) {
        	 throw new ListenerException("复制文件出错:"+e.getMessage());
        }
	    logger.info("复制"+media.getTmpFile().getAbsoluteFile()+"到" + src.getAbsoluteFile()+"成功");
    }

	/* (non-Javadoc)
     * @see net.freestu.looker.common.MediaListener#close()
     */
    @Override
    public void close() throws ListenerException
    {
	    
    }

	/* (non-Javadoc)
     * @see net.freestu.looker.common.MediaListener#commit()
     */
    @Override
    public void commit() throws ListenerException
    {
	    
    }

	/* (non-Javadoc)
     * @see net.freestu.looker.common.MediaListener#delete(net.freestu.looker.common.Media)
     */
    @Override
    public void delete(Media media) throws ListenerException
    {
    	//TODO ...
    }
	/* (non-Javadoc)
     * @see net.freestu.looker.common.MediaListener#init(org.apache.commons.configuration.Configuration)
     */
    @Override
    public void init(Configuration conf) throws ListenerException
    {
	    mediaSaveRoot = conf.getString("mediaSaveRoot");
	    logger.info(mediaSaveRoot);
	    File rootDir = new File(mediaSaveRoot);
	    if(!rootDir.exists())
	    	rootDir.mkdir();
	    logger.info("初始化完成");
	    
    }

	/* (non-Javadoc)
     * @see net.freestu.looker.common.MediaListener#update(net.freestu.looker.common.Media)
     */
    @Override
    public void update(Media media) throws ListenerException
    {
 	    
    }
    
	/**
	 * 返回保存文件目录
	 * 文件保存规则：
	 * media.saveDir/domainName/4位数年-2位数月份/临时文件名
	 * @return File
	 * @throws ListenerException 
	 */
	private File getSaveFile(Media media) throws ListenerException
	{
		//www.domain.com
		StringBuffer saveDirName = new StringBuffer();
		saveDirName.append(URLUtils.domain(media.getUrl()));
		saveDirName.append('/');
		//检查域名文件夹是否存在
		File saveDir = new File(mediaSaveRoot+saveDirName.toString());
		if(!saveDir.exists())
			saveDir.mkdir();
		//www.domain.comm/2009-6/
		Calendar cl = Calendar.getInstance();
		saveDirName.append(cl.get(Calendar.YEAR));
		saveDirName.append("-");
		saveDirName.append(cl.get(Calendar.MONTH));
		//检查目录是否存在，如果不存在，则创建
		saveDir = new File(mediaSaveRoot+saveDirName.toString());
		if(!saveDir.exists())
			saveDir.mkdir();
		//www.domain.com/2009-6/IMAGE/
		saveDirName.append('/'+media.getType().name());
		saveDir = new File(mediaSaveRoot+saveDirName.toString());
		if(!saveDir.exists())
			saveDir.mkdir();
		//保存文件名
		String saveName = Long.toString(media.getDate().getTime())+"-"+media.getName();
		//建立文件
		File saveFile = new File(saveDir.getPath()+'/'+saveName);
		if (!saveFile.exists() && !saveFile.isDirectory())
			return saveFile;
		else {
			throw new ListenerException("令存为的目的地为目录或者文件已经存在");
		}
	}


	
	public String toString()
	{
		return "FileMediaListener";
	}
	 
}
